<?php

class myUser extends sfBasicSecurityUser {

    public function signIn($user) {
        $this->setAuthenticated(true);
        $this->setAttribute('user_id', $user->getId());
        $this->setAttribute('store_id', $user->getStoreId());
        $this->setAttribute('firstname', $user->getFirstname());
        $this->setAttribute('lastname', $user->getLastname());
        $this->setAttribute('name', $user->getFirstname() . '.' . AppTools::utf8_substr($user->getLastname(), 0, 1));

        $this->setPermissions($user->getId());
    }

    public function signOut() {
        $this->getAttributeHolder()->removeNamespace();

        $this->setAuthenticated(false);
        $this->clearCredentials();
    }

    public function getId() {
        return $this->getAttribute('user_id', 0);
    }

    public function getStoreId() {
        return $this->getAttribute('store_id', 0);
    }

    public function getName() {
        return $this->getAttribute('name', '');
    }

    public function getFirstname() {
        return $this->getAttribute('firstname', '');
    }

    public function getLastname() {
        return $this->getAttribute('lastname', '');
    }

    public function getMobile() {
        return $this->getAttribute('mobile', '');
    }

    private function setPermissions($userId) {
        $credentials = PermissionTable::getByUserId($userId);

        foreach ($credentials AS $credential) {
            $credentialName = CredentialsTable::getNameById($credential['credential_id']);
            $this->addCredential($credentialName);
        }

        unset($credential);
    }

    public function getPermissions($userId) {
        $array = array();

        $userPermissions = Doctrine_Core::getTable('Permission')->getByUserId($userId);

        foreach ($userPermissions AS $permission) {
            $array[$permission->getPermissionOption()->getView()] = $permission->getPermissionOption()->getViewName();
        }

        unset($permission);

        return $array;
    }

}
